'use strict'
const { Model } = require('sequelize')
module.exports = (sequelize, DataTypes) => {
  class Category extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      models.Category.hasMany(models.Course, { as: 'courses' })
    }
  }
  Category.init(
    {
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: '分类名称必须填写。' },
          notEmpty: { msg: '分类名称不能为空。' },
          len: { args: [2, 45], msg: '分类名称长度需要在2 ~ 45个字符之间。' },
          async isUnique(value) {
            const category = await Category.findOne({ where: { name: value } })
            if (category) {
              throw new Error(`分类名称：${value} 已存在，请选择其他名称。`)
            }
          },
        },
      },
      rank: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: '排序必须填写。' },
          notEmpty: { msg: '排序不能为空。' },
          isInt: { msg: '排序只能是整数。' },
          min: { args: [1], msg: '排序不能小于0' },
        },
      },
    },
    {
      sequelize,
      modelName: 'Category',
    }
  )
  return Category
}
